package my.http;

import android.os.Handler;
import android.os.Message;

import com.app.ytong.bean.BasisBean;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import my.LogUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;

class MyHttpDownloadCallBack implements Callback {
    private static String tag = "HTTP";
    MyHttpListener mListener;
    ResponderHandler handler;

    String destFileDirPath;
    String destFilePath;
    long mAlreadyDownLength;
    long mTotalLength;

    public MyHttpDownloadCallBack(MyHttpListener mListener, String destFileDirPath, String saveFileName) {
        super();
        this.mListener = mListener;
        this.destFileDirPath = destFileDirPath;
        this.destFilePath = destFileDirPath+"/"+saveFileName;
        handler = new ResponderHandler(this);
    }

    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {
        LogUtil.d(tag, "onFailure: " + e.getMessage());
        if (mListener == null)
            return;
        Message msg = new Message();
        msg.obj = null;
        handler.sendMessage(msg);
        handler.sendEmptyMessage(ResponderHandler.MESSAGE_RESULT_FAILED);

    }


    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        if (mListener == null)
            return;
        ResponseBody responseBody = response.body();
         mTotalLength = responseBody.contentLength();//下载文件的总长度
        InputStream inp = responseBody.byteStream();
        File destFile = new File(destFilePath);
        File destFileDir= new File(destFileDirPath);
        if(!destFileDir.exists()){
            destFileDir.mkdirs();
        }
        if(destFile.exists()){
            destFile.delete();
        }
        if (!destFile.exists()){
//            destFile.mkdir();
            destFile.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(destFile);
        try {
            byte[] bytes = new byte[2048];
            int len = 0;
            while ((len = inp.read(bytes)) != -1) {
                mAlreadyDownLength = mAlreadyDownLength + len;
                fileOutputStream.write(bytes, 0, len);
                if (mListener != null) {
//                    mListener.onProgress(0,mAlreadyDownLength,m);
                    handler.sendEmptyMessage(ResponderHandler.MESSAGE_UPGRADE);
                }
            }
            handler.sendEmptyMessage(ResponderHandler.MESSAGE_RESULT_SUCCESS);
        } catch (Exception e) {
            LogUtil.e(tag, "Get下载异常");
            handler.sendEmptyMessage(ResponderHandler.MESSAGE_RESULT_FAILED);
        } finally {
            fileOutputStream.close();
            inp.close();
            LogUtil.e(tag, "流关闭");
        }

}

private static class ResponderHandler extends Handler {

        public static final int MESSAGE_UPGRADE = 11;
        public static final int MESSAGE_RESULT_SUCCESS  = 12;
        public static final int MESSAGE_RESULT_FAILED  = 13;

    private final MyHttpDownloadCallBack mResponder;

    ResponderHandler(MyHttpDownloadCallBack mResponder) {
        this.mResponder = mResponder;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case MESSAGE_UPGRADE:
                mResponder.mListener.onProgress(0,mResponder.mAlreadyDownLength,mResponder.mTotalLength);
                break;
            case MESSAGE_RESULT_SUCCESS:
                BasisBean basisBean = new BasisBean();
                basisBean.setStatusInfo("下载成功");
                basisBean.setResultData(mResponder.destFilePath);
                mResponder.mListener.onSuccess(0,basisBean);
                mResponder.mListener.onFinish(0);
                break;
            case MESSAGE_RESULT_FAILED:
                mResponder.mListener.onFailure(0, null);
                mResponder.mListener.onFinish(0);
                break;
        }
    }
}

}
